
package com.fas.core.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import com.fas.core.BaseController;
import com.fas.core.plugin.fastdfs.FastDFSClientConfig;
import com.fas.core.util.DateFormatFactory;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;

/**
 * 全局异常处理拦截器
 * 
 * @Copyright: Copyright (c) 2016 FAS 
 * @anthor yixiaoping<thinker1013@163.com>
 * @since 2016年1月23日 下午11:34:27
 * @version V1.0
 */
public class ExceptionInterceptor implements Interceptor {

        private static final Log log = Log.getLog(ExceptionInterceptor.class);
        
        @Override
        public void intercept(Invocation ai) {
                BaseController controller = (BaseController) ai.getController();
                HttpServletRequest request = controller.getRequest();
                try {
                        ai.invoke();
                    	controller.setAttr("fastDFSDownloadUrl", FastDFSClientConfig.me().getDownloadUrl());
                } catch (Exception e) {
                		String errorFlag = "ERROR"+DateFormatFactory.getYyyyMMddHHmmss2(new Date());
                        // 判断是否ajax请求
                        String header = request.getHeader("X-Requested-With");
                        boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
                        String msg = e.getMessage();
                        if (isAjax) {
                        	 	log.error("AJAX_ERROR："+errorFlag, e);
                                controller.returnJsonResult(false,buildErrorTip(errorFlag),null);
                        } else {
                        		log.error("NOAJAX_ERROR："+errorFlag, e);
                                String redirctUrl = request.getHeader("referer");
                                if (StrKit.isBlank(redirctUrl)) {
                                        redirctUrl = request.getRequestURI();
                                }
                                StringWriter sw = new StringWriter();
                                PrintWriter pw = new PrintWriter(sw);
                                try{
                                        e.printStackTrace(pw);
                                        controller.setAttr("exceptions", sw.toString());
                                        controller.setAttr("message", e.toString());
                                        controller.setAttr("redirctUrl", redirctUrl);
                                        controller.setAttr("paramMap",   controller.getParaMap());
                                        controller.renderError(500);
                                }catch(Exception ex){
                                        controller.renderError(500);
                                }finally{
                                        try {
                                                sw.close();
                                        } catch (IOException e1) {
                                                e1.printStackTrace();
                                        }
                                        pw.close();
                                }
                        }
                }
        }
        
        private String buildErrorTip(String errorFlag){
        	StringBuffer sb = new StringBuffer();
        	sb.append("<h4>服务器异常! 如果问题一直存在，请及时联系系统管理员.</h4><br>").
        	append("&nbsp;错误码：<span class='badge badge-warning' style='padding-top:5px;padding-bottom:5px;'>").
        	append(errorFlag).
        	append("</span><br><br>&nbsp;<small>错误码对于问题解决有一定帮助，可以尝试将错误码提供给系统管理员。</small>");
        	return sb.toString();
        }
}
